package com.wef.demo.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.gfa4j.query.Page;
import com.gfa4j.query.QueryInfo;
import com.gfa4j.wef.common.action.CommonQuery4ZTreeAction;
import com.gfa4j.wef.common.action.CommonQueryAction;
import com.gfa4j.wef.entity.TreeNode;
import com.gfa4j.wef.struts.BaseAction;
import com.gfa4j.wef.struts.QueryHandle;
import com.gfa4j.wef.utils.JSONUtil;
import com.wef.demo.entity.Student;
import com.wef.demo.entity.StudentSubject;
import com.wef.demo.service.StudentService;

public class StudentAction extends BaseAction {

	private StudentService studentService;

	public StudentService getStudentService() {
		return studentService;
	}

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public ActionForward queryTreeData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 1.组装QueryInfo
		QueryInfo queryInfo = CommonQueryAction.getQueryInfo(request);
		// 2.查询 并 转换成Json String
		List<String>subTables = new ArrayList<String>();
		subTables.add("studentSubjects");
		List<?> list = (List<?>) QueryHandle.findByQueryInit(queryInfo, subTables);
		String jsonString = JSONArray.fromObject(
				assembleTree((List<Student>) list),
				JSONUtil.getJsonConfig()).toString();

		// 3.输出到页面
		CommonQueryAction.outData2Page(jsonString, response);

		return null;
	}

	/**
	 * TODO 组装树
	 * @param entities
	 * @return
	 */
	private Collection<?> assembleTree(List<Student> entities) {
		Collection<TreeNode> treeNodes = new ArrayList<TreeNode>();
		TreeNode treeNode = null;
		TreeNode treeNode2 = null;
		for (Student entity : entities) {
			treeNode = CommonQuery4ZTreeAction.entity2TreeObject(entity,
					entity.getStudentId(), null, entity.getStudentName(),
					entity.getStudentName(), entity.getStudentSubjects());
			treeNodes.add(treeNode);
			if (treeNode.getChildrenNode() != null
					&& treeNode.getChildrenNode().size() > 0)
				for (Object node : treeNode.getChildrenNode()) {
					//调用entity2TreeObject方法组装树
					treeNode2 = CommonQuery4ZTreeAction.entity2TreeObject(node,
							((StudentSubject) node).getStudentSubjectId(),
							entity.getStudentId(),
							((StudentSubject) node).getSubjectName(),
							((StudentSubject) node).getSubjectName(), null);
					treeNodes.add(treeNode2);
				}
		}

		return treeNodes;
	}

}
